<?php
class AdminSeoController extends BaseController {

	protected $layout = 'admin/layout/default';

	protected $type;

	public function __construct() 
	{
		$this->type = Input::get('type', 'products');
	}

	private function _getItem($type, $itemId)
	{
		switch ($type) {
			case 'categories':
				$item = Category::whereId($itemId)->get(array('id','name'))->first();
				break;
			case 'products':
				$item = Product::whereId($itemId)->get(array('id','name'))->first();
				break;
		}
	
		return $item;
	}
	
	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index() 
	{
		switch ($this->type) {
			case 'categories':
				$lists = Category::with('seo')->get(array('id', 'name')); // Note: Eager Loading
				break;
			case 'products':
				$lists = Product::with('seo')->get(array('id', 'name')); // Note: Eager Loading
				break;
		}
			
// 		header('Content-Type: application/json');
// 		echo $list; die;
// 		echo '<pre>';
// 		dd(DB::getQueryLog());

		$this->layout->content = View::make('admin.seo.index', array('type' => $this->type, 'lists' => $lists));
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		$itemId = Input::get('id');
		$this->layout->content = View::make('admin.seo.create', array('type' => $this->type, 'itemId' => $itemId));
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{		
		$itemId = Input::get('id');
		$item = $this->_getItem($this->type, $itemId);

		$seo = new Seo(Input::all());
		$item->seo()->save($seo);

		Session::flash('message', 'Successfully created SEO!');
		return Redirect::to('admin/seo?type=' . $this->type);
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		$seo = Seo::find($id);		
		$this->layout->content = View::make('admin.seo.edit', array('type' => $this->type, 'seo' => $seo));
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{		
		$seo = Seo::find($id);
		$seo->update(Input::all());

		Session::flash('message', 'Successfully updated SEO!');
		return Redirect::to('admin/seo?type=' . $this->type);
	}
}